<?php declare(strict_types=1);


namespace App\Rpc\Traits\Service;

use App\Rpc\Model\Dao\RoleDao;
use App\Rpc\Model\Dao\UserRoleDao;
use Swoft\Bean\BeanFactory;
use Swoft\Db\DB;
use Swoft\Validator\Exception\ValidatorException;
use App\Rpc\Validator\UserRoleValidator;

/**
 * 公共方法
 * Trait CommonTrait
 * @package App\Rpc\Traits\Service
 */
trait CommonTrait
{
    /**
     * 处理构建user_role关系
     * @param array $data
     * @throws ValidatorException
     * @throws \ReflectionException
     * @throws \Swoft\Bean\Exception\ContainerException
     * @throws \Swoft\Db\Exception\DbException
     */
    private function _user_roles(array $data): void
    {
        //permission_value
        //user_id

        $diyValidator = [
            'UserRoleValidator' => [ 'op' => 'add']
        ];

        //@2添加完以后就要增加运营商和角色关系表，寻找
        $roleDao = BeanFactory::getBean(RoleDao::class);
        $roleInfo = $roleDao->getByWhere([
            'permission_value' => $data['permission_value'],
            ['item_id', '=', $data['permission_value'], 'or']
        ]);
        if(!$roleInfo){
            throw new ValidatorException('您无法创建承运商');
        }

        //@3插入角色人员对应表
        $insert_data = [
            'item_id' => create_item_id(uuid()),
            'user_id' => $data['user_id'],
            'role_id' => $roleInfo['itemId']
        ];

        validate($insert_data, 'UserRoleValidator', [], $diyValidator);

        $userRoleDao = BeanFactory::getBean(UserRoleDao::class);
        $resultRelation = $userRoleDao->insert($insert_data);

        if(!$resultRelation){
            throw new ValidatorException('创建承运商失败', 4003);
        }
    }

    /**
     * 验证字段必须传递
     * @param array $field
     * @param array $data
     * @throws ValidatorException
     */
    private function _requiredFields(array $field, array $data): void
    {
        foreach ($field as $key => $require){
            if(!isset($data[$key]) || !$data[$key]){
                throw new ValidatorException($require, 4002);
            }
        }
    }

    /**
     * 过滤字段
     * @param array $field
     * @param array $data
     * @return array
     */
    private function _filterUpdateFields(array $field, array $data): array
    {

    }
}
